package com.zxy.express.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public final class AESUtils {

    public static final String UTF_8 = "UTF-8";
    public static final String AES = "AES";
    private static final String ASE_EXCEPTION_MESG="aes加密异常";

    private AESUtils(){
        throw new IllegalStateException("AESUtil不允许实例化");
    }
    /**
     * aes加密
     *
     * @param content
     * @param password
     * @return
     */
    public static String aesEncrypts(String content, String password) {
        byte[] result = null;
        try {
            byte[] enCodeFormat = password.getBytes(UTF_8);
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES);// 创建密码器
            byte[] byteContent = content.getBytes(UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            result = cipher.doFinal(byteContent);
        } catch (InvalidKeyException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        } catch (NoSuchAlgorithmException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        } catch (NoSuchPaddingException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        } catch (IllegalBlockSizeException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        } catch (BadPaddingException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        } catch (UnsupportedEncodingException e) {
            log.error(ASE_EXCEPTION_MESG,e);
        }catch (Exception e) {
            log.error(ASE_EXCEPTION_MESG,e);
        }
        // 加密
        return Base64.encodeBase64String(result);

    }

    /**
     * aes 解密
     *
     * @param ciphertext
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws InvalidKeyException
     * @throws IOException
     */
    public static String aesDecrypts(String ciphertext, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
            IOException {
        byte[] enCodeFormat = password.getBytes(UTF_8);
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
        // 创建密码器
        Cipher cipher = Cipher.getInstance(AES);
        // 初始化
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(Base64.decodeBase64(ciphertext));
        return new String(result, UTF_8);
    }

}

